package com.lagou.zk;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import javax.sql.DataSource;
import java.sql.Connection;

public class Client {

    public static void main(String[] args) throws InterruptedException {
        //获取连接客户端
        final ZkClient zkClient = new ZkClient("node01:2181,node02:2181");
        //序列化
        zkClient.setZkSerializer(new ZkStrSerializer());
        //新建存放数据库连接信息的目录
        final boolean exists = zkClient.exists("/database_info");
        if(!exists){
            zkClient.createPersistent("/database_info");
        }
        //监听连接变化
        zkClient.subscribeDataChanges("/database_info", new IZkDataListener() {
            public void handleDataChange(String s, Object o) throws Exception {
                //获取连接数据
                String[] split = o.toString().split(",");
                //创建连接池
                DataSource dataSource = DruidUtils.getDataSource(split[0], split[1], split[2]);
                Connection connection = dataSource.getConnection();
                //打印当前连接信息
                System.out.println("当前连接url:" + split[0]);


            }

            public void handleDataDeleted(String s) throws Exception {

            }
        });
        Thread.sleep(Integer.MAX_VALUE);
    }


}
